﻿@using Smartstore.Utilities

@functions{
    private DateTime? Value
    {
        get
        {
            DateTime? value = null;
            if (ViewData.Model != null)
            {
                value = Convert.ToDateTime(ViewData.Model, System.Globalization.CultureInfo.CurrentCulture).ToLocalTime();
            }
            return value;
        }
    }

    private bool PickTime
    {
        get
        {
            if (TryGetMetadata<bool>("pickTime", out var result))
            {
                return result;
            }
            else if (TryGetMetadata<List<string>>("pickTimeFieldIds", out var ids))
            {
                var id = ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty);
                return ids.Contains(id);
            }

            return false;
        }
    }

    private string CssClass
    {
        get
        {
            var cls = "input-group date datetimepicker-group flex-nowrap";

            if (TryGetMetadata<string>("size", out var size))
            {
                cls += " input-group-" + size;
            }

            return cls;
        }
    }
}

@{
    var id = Html.IdForModel();
    var name = Html.NameForModel();
    var format = PickTime ? "L LT" : "L";
    var value = string.Empty;
    if (Value.HasValue && Value.Value > DateTime.MinValue)
    {
        value = PickTime ? Value.Value.ToString() : Value.Value.ToShortDateString();
    }
    var attributes = new AttributeDictionary().Merge(ConvertUtility.ObjectToDictionary(ViewData["htmlAttributes"] ?? new object()));
}

<div class="@CssClass" id="@id-parent" data-date="@value" data-target-input="nearest" data-keep-open="false">
    <input asp-for="@Model"
           attrs="attributes"
           class="datetimepicker-input edit-control"
           data-target="#@(id)-parent"
           data-format="@format"
           data-use-current="false"
           data-editor="date-time"
           type="text"
           attr-value="(value.HasValue(), value)" />

    <div class="input-group-append input-group-addon" data-target="#@(id)-parent" data-toggle="datetimepicker">
        <span class="input-group-text">
            <i class="far fa-calendar"></i>
        </span>
    </div>
</div>